import random
from django.contrib import auth as django_auth
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from django.core.cache import cache
from django.conf import settings
from django.contrib.auth.models import User
from django.db import transaction

from account import models as models_account
from account import tasks
from utils import utils
from sorl.thumbnail import get_thumbnail


def validate_sms_code(phone, value):
    key = settings.SMS_RECORD_CACHE_KEY_PREFIX + phone
    cached = cache.get(key)
    if not cached:
        raise serializers.ValidationError('验证码失效，请重新验证！')
    if not cached == value:
        raise serializers.ValidationError('验证码输入错误！')

    tasks.update_sms_record_status_task.delay(phone, {'status': '1'})
    cache.delete(key)
    return value


class AccountLoginSerializer(serializers.Serializer):
    username = serializers.CharField(write_only=True)
    password = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)


class AccountProfileSerializer(serializers.ModelSerializer):
    # user_permissions = serializers.SerializerMethodField()

    class Meta:
        model = models_account.Account
        fields = (
            # 'user_permissions',
            'phone', 'real_name', 'nickname', 'college', 'role',
        )

    # def get_user_permissions(self, obj):
    #     request = self.context.get('request')
    #     if request:
    #         return request.user.get_all_permissions()
    #     return []

    def update(self, instance, data):
        super(AccountSerializer, self).update(instance, data)


class AccountSerializer(serializers.Serializer):
    phone=serializers.CharField(required=True)
    email=serializers.EmailField(required=True)
    college = serializers.CharField(required=True)
    real_name = serializers.CharField(required=True)
    nickname = serializers.CharField(required=True)




class SmsRecordSerializer(serializers.ModelSerializer):
    phone = serializers.CharField(write_only=True)
    code = serializers.CharField(read_only=True)

    class Meta:
        model = models_account.SmsRecord
        fields = ('phone', 'code','is_for')

    def validate_phone(self, value):
        if not utils.is_phone(value):
            raise serializers.ValidationError('手机号格式错误！')

        key = settings.SMS_RECORD_CACHE_KEY_PREFIX + value
        if cache.get(key):
            raise serializers.ValidationError('验证码已经发送！')
        return value

    def create(self, validated_data):
        phone = validated_data['phone']
        is_for=validated_data['is_for']
        accounts=models_account.Account.objects.filter(phone=phone)
        if(is_for=='1'):
            if accounts.exists():
                raise serializers.ValidationError('该手机号已经注册！')
        elif (is_for=='2'):
            if not accounts.exists():
                raise serializers.ValidationError('该手机号未注册！')

        code = str(random.randint(1000, 9999))

        sms_record = models_account.SmsRecord.objects.create(
            code=code,
            status='0',
            phone=phone,
        )
        # Celery 异步发送
        print("开始发送短新！")
        tasks.send_sms_code_task.delay(phone, code)
        return sms_record


class AccountInfoSerializer(serializers.ModelSerializer):
    class_id=serializers.SerializerMethodField()

    class Meta:
        model=models_account.Account
        fields = ('class_id','user','real_name','nickname',
                    'email','role','member_id','gender','phone',
                  'phone_confirmation_time','college','avatar','avatar_thumb',)

    def get_class_id(self,obj):
        class_id=None
        if  obj.role == '1':
            class_id = models_account.StudentInfo.objects.get(id=obj.member_id).class_id
            try:
               pass
            except:
                print('error role=1')
                pass
        elif obj.role == '2':
            class_id = models_account.TeacherInfo.objects.get(id=obj.member_id).class_id
            try:
                pass
            except:
                print('error role=2')
                pass
        print(class_id)
        return class_id


class AccountChangePwdSerializer(serializers.Serializer):
    old_password = serializers.CharField(
        min_length=6,
        max_length=16,
        write_only=True,
    )

    password = serializers.CharField(
        min_length=6,
        max_length=16,
        write_only=True,
    )

    def validate(self, data):
        user = self.context['request'].user
        old_password = data['old_password']
        user = django_auth.authenticate(
            username=user.username,
            password=old_password
        )
        if user is not None and user.is_active:
            return data
        else:
            raise serializers.ValidationError({
                'old_password': '原密码错误'
            })

    def set_password(self, data):
        user = self.context['request'].user
        user.set_password(data['password'])
        user.save()
        try:
            token = Token.objects.get(user=user)
            token.delete()
            Token.objects.create(user=user)
        except Token.DoesNotExist:
            token, _ = Token.objects.get_or_create(user=user)


class AccountAvatarSerializer(serializers.Serializer):
    avatar = serializers.ImageField(required=False)

    def update(self, instance, validated_data):
        avatar=validated_data['avatar']
        #生成压缩图片
        if avatar:
            resized_avatar = get_thumbnail(avatar, '150x150',crop='center',
                                   quality=99)
            instance.avatar_thumb=resized_avatar.url
        instance.avatar = avatar
        instance.save()
        return instance

class AccountResetPwdSerializer(serializers.Serializer):
    phone=serializers.CharField(required=True, write_only=True)
    sms_code=serializers.CharField(required=True, write_only=True)
    password=serializers.CharField(required=True, write_only=True)
